package com.example.ui.share;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import com.example.huashangapp.R;
import com.example.net.NetRequest;
import com.example.ui.share.CreateCircleGroupActivity;
import com.example.ui.share.IndustryFragment;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.RadioGroup.OnCheckedChangeListener;

public class CreateCircleGroup extends Fragment {
	public static ImageView ccg_selectpic;
//	private TextView circleNameText, circleIntroduceText;
	private EditText circleNameEdit, circleIntroduceEdit;
	private RadioGroup circleOpenGroup, circleJoinGroup;
	private RadioButton openShareButton,openNotShareButton,joinApplyButton,joinFreeButton;
	CreateCircleGroupActivity ccg;

	private RelativeLayout ccg_l_industry, ccg_l_city;
	private TextView ccg_txt_industry, ccg_txt_city;
	private Bitmap photo;
	private String imagenames;
	View v;

	int openType = 1;
	int joinType = 1;
	
	String ccStr,ccHeadImg,ccName,ccIntroduce;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		v = inflater.inflate(R.layout.ccgfragment, null);
		ccg = (CreateCircleGroupActivity) getActivity();
		ccStr = ccg.ccgStr;
		ccHeadImg = ccg.ccgHeadImg;
		ccName  = ccg.ccgName;
		ccIntroduce = ccg.ccgIntroduce;

		ccg_selectpic = (ImageView) v.findViewById(R.id.create_circle_gridview);
		circleNameEdit = (EditText) v.findViewById(R.id.create_circle_name_edittext);
		circleIntroduceEdit = (EditText) v.findViewById(R.id.create_circle_brief_introduce_edittext);
		ccg_l_industry = (RelativeLayout) v.findViewById(R.id.cc_rlindustry);
		ccg_l_city = (RelativeLayout) v.findViewById(R.id.cc_rlcity);
		ccg_txt_industry = (TextView) v.findViewById(R.id.cc_btn_industry);
		ccg_txt_city = (TextView) v.findViewById(R.id.cc_tvcity);
		circleOpenGroup = (RadioGroup) v.findViewById(R.id.create_circle_open_degree_radiogroup);
		circleJoinGroup = (RadioGroup) v.findViewById(R.id.create_circle_join_way_radiogroup);
		openShareButton = (RadioButton)v.findViewById(R.id.create_circle_open_degree_share);
		openNotShareButton = (RadioButton)v.findViewById(R.id.create_circle_open_degree_not_share);
		joinApplyButton = (RadioButton)v.findViewById(R.id.create_circle_join_apply);
		joinFreeButton =(RadioButton)v.findViewById(R.id.create_circle_join_freedom);

		if("create".equals(ccStr)){
			if (!ccg.circleIndustry.equals("")) {
				ccg_txt_industry.setText(ccg.circleIndustry);
			}
			if (!ccg.province.equals("") && !ccg.city.equals("")) {
				ccg_txt_city.setText(ccg.province + "\t" + ccg.city);
			}
			if (!ccg.Filename.equals("")) {
				Bitmap b = BitmapFactory.decodeFile(ccg.Filename);
				ccg_selectpic.setImageBitmap(b);
			}
		}else{
			try {
				Bitmap bm = BitmapFactory.decodeFile(ccHeadImg);
				ccg_selectpic.setImageBitmap(bm);
			} catch (Exception e) {
				ccg_selectpic.setBackgroundResource(R.drawable.head_bg);
				e.printStackTrace();
			}
			ccg_txt_industry.setVisibility(View.GONE);
			ccg_txt_city.setVisibility(View.GONE);
			circleNameEdit.setVisibility(View.VISIBLE);
			circleIntroduceEdit.setVisibility(View.VISIBLE);
			circleNameEdit.setText(ccName);
			circleIntroduceEdit.setText(ccIntroduce);
//			circleNameEdit.setText(ccg.circleName);
//			circleIntroduceEdit.setText(ccg.circleIntroduce);
			ccg_txt_industry.setText(ccg.circleIntroduce);
			ccg_txt_city.setText(ccg.province+ "\t" +ccg.city+"");
			if("0".equals(ccg.isOpen)){
				openNotShareButton.setChecked(true);
			}else if("1".equals(ccg.isOpen)){
				openShareButton.setChecked(true);
			}
			
			if("0".equals(ccg.isJoin)){
				joinApplyButton.setChecked(true);
			}else if("1".equals(ccg.isJoin)){
				joinFreeButton.setChecked(true);
			}
		}
		
		circleOpenGroup
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(RadioGroup group, int checkedId) {
						// TODO Auto-generated method stub
						switch (checkedId) {
						case R.id.create_circle_open_degree_share:
							openType = 1;

							break;
						case R.id.create_circle_open_degree_not_share:
							openType = 0;

							break;
						default:
							break;
						}
					}
				});
		circleJoinGroup
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(RadioGroup group, int checkedId) {
						// TODO Auto-generated method stub
						switch (checkedId) {

						case R.id.create_circle_join_apply:
							joinType = 0;
							break;
						case R.id.create_circle_join_freedom:
							joinType = 1;
							break;

						default:
							break;
						}
					}
				});

		ccg_l_industry.setOnClickListener(ccg_ocl);
		ccg_l_city.setOnClickListener(ccg_ocl);
		ccg_selectpic.setOnClickListener(ccg_ocl);
		return v;
	}

	void getdata() {
		ccg.circleName = circleNameEdit.getText().toString();
		ccg.circleIntroduce = circleIntroduceEdit.getText().toString();
		
		ccg.isJoin = joinType;
		ccg.isOpen = openType;
		
	}

	Runnable ccgsumbit_pic = new Runnable() {

		@Override
		public void run() {
			NetRequest.CircleuploadPic(v.getContext(), ccg.Filename);

		}
	};

	private OnClickListener ccg_ocl = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.create_circle_gridview:
				getPicFromContent();

				break;
			case R.id.cc_rlindustry:
				FragmentManager fm = getFragmentManager();
				IndustryFragment inf = new IndustryFragment();
				inf.type = 3;
				FragmentTransaction ft = fm.beginTransaction();
				ft.replace(R.id.cc_rl, inf);
				ft.addToBackStack(null);
				ft.commit();
				break;
			case R.id.cc_rlcity:
				FragmentManager fm2 = getFragmentManager();
				CircleSelectprovince csc = new CircleSelectprovince();
				FragmentTransaction ft2 = fm2.beginTransaction();
				ft2.replace(R.id.cc_rl, csc);
				ft2.addToBackStack(null);
				ft2.commit();
				break;

			default:
				break;
			}
		}
	};

	private void getPicFromContent() {
		try {
			Intent album = new Intent(Intent.ACTION_GET_CONTENT);
			album.setType("image/*");
			startActivityForResult(album, 2);
		} catch (ActivityNotFoundException e) {
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (requestCode == 1) {

			startPhotoZoom(Uri.fromFile(new File(ccg.Filename)));

		} else if (requestCode == 2) {

			if (data != null) {

				Uri uri = data.getData();// 可以得到图片在Content：//。。。中的地址，把它转化成绝对地址如下
				String[] proj = { MediaStore.Images.Media.DATA };

				// 参数：proj 是指查哪一列
				Cursor cursor = ccg.managedQuery(uri, proj, null, null, null);

				if (cursor != null) {
					int column_index = cursor
							.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
					if (cursor.getCount() > 0 && cursor.moveToFirst()) {
						ccg.Filename = cursor.getString(column_index);
						String name = ccg.Filename.substring(ccg.Filename
								.lastIndexOf("/"));
						imagenames = System.currentTimeMillis()
								+ name.substring(name.indexOf("."));
						startPhotoZoom(data.getData());
					}

				}

			}

		} else if (requestCode == 3) {
			/**
			 * 非空判断大家一定要验证，如果不验证的话， 在剪裁之后如果发现不满意，要重新裁剪，丢弃
			 * 当前功能时，会报NullException，可以根据不同情况在合适的 地方做判断处理类似情况
			 * 
			 */
			if (data != null) {
				try {
					setPicToView(data);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		} else {
			ccg.finish();
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * 剪裁图片的方法
	 * 
	 * 
	 */
	private void startPhotoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		// 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 100);
		intent.putExtra("outputY", 100);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, 3);
	}

	/**
	 * 保存剪裁之后的图片
	 * 
	 * 
	 */
	private void setPicToView(Intent picdata) throws IOException {
		Bundle extras = picdata.getExtras();
		if (extras != null) {
			photo = extras.getParcelable("data");
			// 压缩
			photo = imageZoom(photo);
			File f1 = new File(ccg.getCacheDir(), imagenames);
			ccg.Filename = ccg.getCacheDir() + "/" + imagenames;
			savePic(photo, f1.getPath());
			ccg_selectpic.setImageBitmap(photo);
			new Thread(ccgsumbit_pic).start();

		}

	}

	public Bitmap imageZoom(Bitmap bitMap) {
		// 图片允许最大空间 ：单位：KB
		double maxSize = 200.00;
		// 将bitmap放至数组中，意在bitmap的大小（与实际读取的原文件要大）
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bitMap.compress(Bitmap.CompressFormat.JPEG, 70, baos);// 70 -- 压缩率 ；
																// 100是不压缩、压缩率为0；
		byte[] b = baos.toByteArray();

		// 将字节换成KB
		double mid = b.length / 1024;
		// 判断bitmap占用空间是否大于允许最大空间 如果大于则压缩 小于则不压缩
		if (mid > maxSize) {
			// 获取bitmap大小 是允许最大大小的多少倍
			double i = mid / maxSize;
			// 开始压缩 此处用到平方根 将宽带和高度压缩掉对应的平方根倍
			// （1.保持刻度和高度和原bitmap比率一致，压缩后也达到了最大大小占用空间的大小）
			bitMap = zoomImage(bitMap, bitMap.getWidth() / Math.sqrt(i),
					bitMap.getHeight() / Math.sqrt(i));
			return bitMap;
		}

		return bitMap;
	}

	public static void savePic(Bitmap b, String strFileName) {
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(strFileName);
			if (null != fos) {
				b.compress(Bitmap.CompressFormat.PNG, 70, fos);
				fos.flush();
				fos.close();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/***
	 * 图片的缩放方法
	 * 
	 * @param bgimage
	 *            ：源图片资源
	 * @param newWidth
	 *            ：缩放后宽度
	 * @param newHeight
	 *            ：缩放后高度
	 * @return
	 */
	public static Bitmap zoomImage(Bitmap bgimage, double newWidth,
			double newHeight) {
		// 获取这个图片的宽和高
		float width = bgimage.getWidth();
		float height = bgimage.getHeight();
		// 创建操作图片用的matrix对象
		Matrix matrix = new Matrix();
		// 计算宽高缩放率
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		// 缩放图片动作
		matrix.postScale(scaleWidth, scaleHeight);
		Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width,
				(int) height, matrix, true);
		return bitmap;
	}

}
